package com.ccnu.JobHub.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccnu.JobHub.common.util.Token;
import com.ccnu.JobHub.model.common.Result;
import com.ccnu.JobHub.model.database.*;
import com.ccnu.JobHub.model.request.*;
import com.ccnu.JobHub.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("post")
@CrossOrigin("*")
@Slf4j
public class PostController {

    private final PostService postService;
    private final ViewPostService viewPostService;
    private final StudentService studentService;
    private final CommentService commentService;
    private final StarRelationService starRelationService;
    private final CommentLikeService commentLikeService;
    private final PostLikeService postLikeService;
    private final PostTagService postTagService;

    /**
     * 构造函数
     * @param postService 帖子
     * @param viewPostService 升学帖
     * @param studentService 学生
     * @param commentService 评论
     * @param starRelationService 点赞关系
     * @param commentLikeService 评论点赞
     * @param postLikeService 帖子点赞
     */
    public PostController(PostService postService, ViewPostService viewPostService, StudentService studentService, CommentService commentService, StarRelationService starRelationService, CommentLikeService commentLikeService, PostLikeService postLikeService, PostTagService postTagService) {
        this.postService = postService;
        this.viewPostService = viewPostService;
        this.studentService = studentService;
        this.commentService = commentService;
        this.starRelationService = starRelationService;
        this.commentLikeService = commentLikeService;
        this.postLikeService = postLikeService;
        this.postTagService = postTagService;
    }

    /**
     * 返回广场推荐帖
     * @param page 当前页码
     * @param pageSize 页面大小
     * @param type 升学贴还是就业贴
     * @return 一个Result结果
     */
    @GetMapping("recommendations")
    public Result recommendations(@RequestParam("page") Integer page,@RequestParam("pageSize") Integer pageSize,@RequestParam("type") String type,@RequestParam("select") String select){
        log.info("--------------------返回广场推荐帖子请求--------------------");
        List<ViewPost> posts;
        if (type.equals("Enrollment")){
            posts = viewPostService.listEnrollmentPost(page,pageSize,select);
//            System.out.println(posts);
        }
        else{
            posts = viewPostService.listJobPost(page,pageSize,select);
        }
        if (posts == null || posts.isEmpty()){
            return Result.error("数据库里没有帖子");
        }
        return Result.success("显示广场推荐帖子成功",posts);
    }

    /**
     *获得某id的帖子内容，用于转发贴的内容
     * @param PostId 帖子对应的id
     * @return 返回对应帖子的内容
     */
    @GetMapping("getPostById")
    public Result getById(@RequestParam("postId") String PostId){
        log.info("根据帖子id查看内容请求");
        Post post = postService.getById(PostId);
        if (post==null){
            return Result.error("不存在该帖子");
        }
        Student student = studentService.getById(post.getStudentId());
        post.setNickname(student.getNickname());
//        post.setAvatar(student.getAvatar()); 因为现在使用接口来获取头像了，而不是本地url了
        return Result.success("返回对应帖子成功", post);
    }

    /**
     * 查看评论
     * @param postId 评论id
     * @return 返回一个评论列表
     */
    @GetMapping("comments")
    public Result comments(@RequestParam("postId") String postId){
        log.info("--------------------返回评论列表请求--------------------");
        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<Comment>()
                .eq("post_id",postId)
                .isNull("parent_comment_id")
                .orderByAsc("created_at");

        List<Comment> comments = commentService.list(commentQueryWrapper);
        if(comments.isEmpty()){
            return Result.success("当前帖子无评论",comments);
        }
        for (Comment comment : comments) {
            List<Comment> sonComments = new ArrayList<>();

            comment.setNickname(studentService.getById(comment.getStudentId()).getNickname());
            findChildren(comment,sonComments);
            comment.setSonComments(sonComments);

        }
        return Result.success("查看评论成功", comments);
    }
    // 这里是获取一级评论的子评论
    public void findChildren(Comment parent,List<Comment> fatherChildren){
//        给所有的二级评论设置回复的对象名字
        List<Comment> comments = commentService.getSonCommentsByParentId(parent.getCommentId());
        for (Comment comment : comments){
//            如果二级子评论还有子评论获取并放到一级子评论的子评论里，与二级子评论并列
            if (!commentService.getSonCommentsByParentId(comment.getCommentId()).isEmpty()){
                findChildren(comment,fatherChildren);
            }
//            给所有的二级评论设置昵称
            comment.setNickname(studentService.getById(comment.getStudentId()).getNickname());
//            给所有的二级评论设置回复的对象名字
            comment.setReplyName(studentService.getById(parent.getStudentId()).getNickname());
            fatherChildren.add(comment);
            comment.setSonComments(new ArrayList<>());
        }

    }

    /**
     * 获取评论条数
     * @param postId 对应的帖子id
     * @return 一个Result结果
     */
    @GetMapping("commentsCount")
    public Result commentsCount(@RequestParam("postId") String postId){
        log.info("--------------------获取评论条数请求--------------------");
        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<Comment>()
                .eq("post_id",postId);
        long count = commentService.count(commentQueryWrapper);
        return Result.success("获取评论条数成功",count);
    }

    /**
     * 获取评论条数
     * @param studentId 学生学号
     * @return 一个Result结果
     */
    @GetMapping("postsCount")
    public Result postsCount(@RequestParam("studentId") String studentId){
        log.info("--------------------获取帖子条数请求--------------------");
        QueryWrapper<Post> postQueryWrapper = new QueryWrapper<Post>()
                .eq("student_id",studentId);
        long count = postService.count(postQueryWrapper);
        return Result.success("获取帖子条数成功",count);
    }

    /**
     * 帖子点赞点踩
     * @param postIsLikeRequest 可以包含是帖子还是评论，然后是点赞还是点踩，然后是取消还是正常点
     * @return 返回一个成功的消息
     */
    @PutMapping("postIsLike")
    public Result postIsLike(@RequestHeader("token") String token,@RequestBody PostIsLikeRequest postIsLikeRequest){
        log.info("--------------------帖子点赞点踩请求--------------------");
        String studentId = Token.inspectOldToken(token);
        QueryWrapper<PostLike> postLikeQueryWrapper = new QueryWrapper<PostLike>()
                .eq("student_id",studentId)
                .eq("post_id",postIsLikeRequest.getPostId());
        PostLike postLike = postLikeService.getOne(postLikeQueryWrapper);
        if (postLike == null){
            PostLike postLike1 = new PostLike();
            postLike1.setPostId(postIsLikeRequest.getPostId());
            postLike1.setStudentId(Integer.valueOf(studentId));
            postLike1.setStatus(postIsLikeRequest.getStatue());
            postLikeService.save(postLike1);
            if(postIsLikeRequest.getStatue().equals(1)){
                postLike(postIsLikeRequest.getPostId(), "1");
            }
            else if (postIsLikeRequest.getStatue().equals(-1)){
                postDislike(postIsLikeRequest.getPostId(), "1");
            }
            else Result.error("已经是无状态了");

            return Result.success("点赞/点踩成功");
        }
        if (postLike.getStatus().equals(0)){
            if(postIsLikeRequest.getStatue().equals(1)){
                postLike(postIsLikeRequest.getPostId(), "1");
            }
            else if (postIsLikeRequest.getStatue().equals(-1)){
                postDislike(postIsLikeRequest.getPostId(), "1");
            }
            else Result.error("已经是无状态了");
        }
        else if (postLike.getStatus().equals(1)){
            if (postIsLikeRequest.getStatue().equals(0)){
                postLike(postIsLikeRequest.getPostId(),"-1");
            }
            else if (postIsLikeRequest.getStatue().equals(-1)){
                postLike(postIsLikeRequest.getPostId(),"-1");
                postDislike(postIsLikeRequest.getPostId(),"1");
            }
            else Result.error("已经点过赞了");
        }
        else {
            if (postIsLikeRequest.getStatue().equals(0)){
                postDislike(postIsLikeRequest.getPostId(),"-1");
            }
            else if (postIsLikeRequest.getStatue().equals(1)){
                postLike(postIsLikeRequest.getPostId(),"1");
                postDislike(postIsLikeRequest.getPostId(),"-1");
            }
            else Result.error("已经点过踩了");
        }
        postLike.setStatus(postIsLikeRequest.getStatue());
        postLikeService.saveOrUpdate(postLike);
        return Result.success("点赞/点踩成功");
    }    /**

     * 评论点赞点踩
     * @param commentIsLikeRequest 包含一个评论id，以及点赞之后的状态
     * @return 返回一个成功的消息
     */
    @PutMapping("commentIsLike")
    public Result commentIsLike(@RequestHeader("token") String token,@RequestBody CommentIsLikeRequest commentIsLikeRequest){
        log.info("--------------------评论点赞点踩请求--------------------");
        String studentId = Token.inspectOldToken(token);
        QueryWrapper<CommentLike> commentLikeQueryWrapper = new QueryWrapper<CommentLike>()
                .eq("student_id",studentId)
                .eq("comment_id",commentIsLikeRequest.getCommentId());
        CommentLike commentLike = commentLikeService.getOne(commentLikeQueryWrapper);
        if (commentLike == null){
            CommentLike commentLike1 = new CommentLike();
            commentLike1.setCommentId(commentIsLikeRequest.getCommentId());
            commentLike1.setStudentId(Integer.valueOf(studentId));
            commentLike1.setStatus(commentIsLikeRequest.getStatue());
            commentLikeService.save(commentLike1);
            if(commentIsLikeRequest.getStatue().equals(1)){
                commentLike(commentIsLikeRequest.getCommentId(), "1");
            }
            else if (commentIsLikeRequest.getStatue().equals(-1)){
                commentDislike(commentIsLikeRequest.getCommentId(), "1");
            }
            else Result.error("已经是无状态了");
            return Result.success("点赞/点踩成功");
        }
        if (commentLike.getStatus().equals(0)){
            if(commentIsLikeRequest.getStatue().equals(1)){
                commentLike(commentIsLikeRequest.getCommentId(), "1");
            }
            else if (commentIsLikeRequest.getStatue().equals(-1)){
                commentDislike(commentIsLikeRequest.getCommentId(), "1");
            }
            else Result.error("已经是无状态了");
        }
        else if (commentLike.getStatus().equals(1)){
            if (commentIsLikeRequest.getStatue().equals(0)){
                commentLike(commentIsLikeRequest.getCommentId(),"-1");
            }
            else if (commentIsLikeRequest.getStatue().equals(-1)){
                commentLike(commentIsLikeRequest.getCommentId(),"-1");
                commentDislike(commentIsLikeRequest.getCommentId(),"1");
            }
            else Result.error("已经点过赞了");
        }
        else {
            if (commentIsLikeRequest.getStatue().equals(0)){
                commentDislike(commentIsLikeRequest.getCommentId(),"-1");
            }
            else if (commentIsLikeRequest.getStatue().equals(1)){
                commentLike(commentIsLikeRequest.getCommentId(),"1");
                commentDislike(commentIsLikeRequest.getCommentId(),"-1");
            }
            else Result.error("已经点过踩了");
        }
        commentLike.setStatus(commentIsLikeRequest.getStatue());
        commentLikeService.saveOrUpdate(commentLike);
        return Result.success("点赞/点踩成功");
    }

    private void postLike(Integer postId, String  a) {
        UpdateWrapper<Post> postUpdateWrapper = new UpdateWrapper<Post>()
                .eq("post_id", postId)
                .setSql("like_num = like_num + "+a);
        postService.update(postUpdateWrapper);
    }
    private void postDislike(Integer postId, String  a) {
        UpdateWrapper<Post> postUpdateWrapper = new UpdateWrapper<Post>()
                .eq("post_id", postId)
                .setSql("dislike = dislike + "+a);
        postService.update(postUpdateWrapper);
    }
    private void commentLike(Integer commentId, String  a) {
        UpdateWrapper<Comment> commentUpdateWrapper = new UpdateWrapper<Comment>()
                .eq("comment_id", commentId)
                .setSql("like_num = like_num + "+a);
        commentService.update(commentUpdateWrapper);
    }
    private void commentDislike(Integer commentId, String  a) {
        UpdateWrapper<Comment> commentUpdateWrapper = new UpdateWrapper<Comment>()
                .eq("comment_id", commentId)
                .setSql("dislike = dislike + "+a);
        commentService.update(commentUpdateWrapper);
    }

    /**
     * 给帖子底下添加评论
     * @param token 放在请求头，用来验证和获取对应的学生id
     * @param newCommentRequest 这里是评论的一些内容
     * @return 成功添加
     */
    @PostMapping("newComment")
    public Result newComment(@RequestHeader("token") String token ,@RequestBody NewCommentRequest newCommentRequest){
        log.info("--------------------添加评论请求--------------------");
        String studentId = Token.inspectOldToken(token);
        LocalDateTime currentTime = LocalDateTime.now();
        Comment comment = new Comment();
        comment.setPostId(newCommentRequest.getPostId());
        comment.setStudentId(Integer.valueOf(studentId));
        comment.setContent(newCommentRequest.getContent());
        comment.setCreatedAt(Timestamp.valueOf(currentTime));
        commentService.save(comment);
        return Result.success("添加评论成功",comment);
    }

    /**
     * 给评论添加一条回复的评论
     * @param token 放在请求头，用来验证和获取对应的学生id
     * @param newCommentRequest 这里是评论的一些内容
     * @return 成功添加
     */
    @PostMapping("comment/newComment")
    public Result comment_newComment(@RequestHeader("token") String token ,@RequestBody NewCommentRequest2 newCommentRequest){
        log.info("--------------------添加回复的评论请求--------------------");
        String studentId = Token.inspectOldToken(token);
        LocalDateTime currentTime = LocalDateTime.now();
        Comment comment = new Comment();
        Comment comment1 = commentService.getById(newCommentRequest.getCommentId());

        comment.setPostId(comment1.getPostId());
        comment.setParentCommentId(newCommentRequest.getCommentId());
        comment.setStudentId(Integer.valueOf(studentId));
        comment.setContent(newCommentRequest.getContent());
        comment.setCreatedAt(Timestamp.valueOf(currentTime));
        commentService.save(comment);
        return Result.success("添加评论成功",comment);
    }

    /**
     * 用来转发喜欢的帖子到自己的主页里面
     * @param token 放在请求头，用来验证和获取对应的学生id
     * @param shareRequest 转发贴的一些内容
     * @return 返回成功添加
     */
    @PostMapping("share")
    public Result share(@RequestHeader("token") String token ,@RequestBody NewCommentRequest shareRequest){
        log.info("--------------------转发帖子请求--------------------");
        String studentId = Token.inspectOldToken(token);
        Post post = new Post();
        Post post1 = postService.getById(shareRequest.getPostId());
        if (post1.getIsShare() == 0){
            post.setSharePostId(shareRequest.getPostId());
        }
        else {
            post.setSharePostId(post1.getSharePostId());
        }

        LocalDateTime currentTime = LocalDateTime.now();
        post.setContent(shareRequest.getContent());
        post.setCreatedAt(Timestamp.valueOf(currentTime));
        post.setUpdatedAt(Timestamp.valueOf(currentTime));
        post.setIsShare(1);
        post.setTitle("转发贴");
        post.setStatus(0);
        post.setStudentId(Integer.valueOf(studentId));
        postService.save(post);

        QueryWrapper<PostTag> postQueryWrapper = new QueryWrapper<PostTag>()
                .eq("post_id",post.getSharePostId())
                .in("tag_id",1,2);
        PostTag postTag = postTagService.getOne(postQueryWrapper);
        PostTag postTag1 = new PostTag();
        postTag1.setPostId(post.getPostId());
        postTag1.setTagId(postTag.getTagId());
        postTagService.save(postTag1);

        return Result.success("转发帖子成功");
    }

    /**
     * 显示关注的人的贴子
     * @param token token令牌
     * @param pageRequest 分页的内容
     * @return Result结果
     */
    @GetMapping("followPost")
    public Result followPost(@RequestHeader("token") String token,@ModelAttribute PageRequest pageRequest){
        log.info("--------------------显示关注的帖子请求--------------------");
        String studentId = Token.inspectOldToken(token);

        QueryWrapper<StarRelation> starRelationQueryWrapper = new QueryWrapper<StarRelation>()
                .eq("student_id",studentId)
                .select("star_student_id");
        List<Integer> starRelations = starRelationService.listObjs(starRelationQueryWrapper,obj -> (Integer) obj);
        if (starRelations==null || starRelations.isEmpty()){
            return Result.error("您当前无关注用户");
        }
        QueryWrapper<Post> postQueryWrapper = new QueryWrapper<Post>()
                .orderByDesc("updated_at")
                .in("student_id",starRelations)
                .eq("status",1);
        Page<Post> page = Page.of(pageRequest.getPage(),pageRequest.getPageSize());
        List<Post> posts = postService.list(page,postQueryWrapper);
        for (Post post : posts){
            Student student = studentService.getById(post.getStudentId());
            post.setNickname(student.getNickname());
//            post.setAvatar(student.getAvatar()); 因为现在使用接口来获取头像了，而不是本地url了
        }
        return Result.success("显示关注的帖子成功",posts);
    }

    /**
     * 显示点赞点踩状态请求
     * @param token token令牌
     * @param type 类型
     * @return Result结果
     */
    @GetMapping("showLikeStatus")
    public Result showLikeStatus (@RequestHeader("token") String token,@RequestParam("type")String type, @RequestParam("id")String id){
        log.info("--------------------显示点赞点踩状态请求--------------------");
        String studentId = Token.inspectOldToken(token);
        if (type.equals("post")){
            QueryWrapper<PostLike> postLikeQueryWrapper = new QueryWrapper<PostLike>()
                    .eq("student_id",studentId)
                    .eq("post_id",id);
            PostLike postLike = postLikeService.getOne(postLikeQueryWrapper);
            if(postLike == null){
                return Result.success("成功显示点赞点踩状态",0);
            }
            return Result.success("成功显示点赞点踩状态",postLike.getStatus());
        }
        else {
            QueryWrapper<CommentLike> commentLikeQueryWrapper = new QueryWrapper<CommentLike>()
                    .eq("student_id",studentId)
                    .eq("comment_id",id);
            CommentLike commentLike = commentLikeService.getOne(commentLikeQueryWrapper);
            if(commentLike == null){
                return Result.success("成功显示点赞点踩状态",0);
            }
            return Result.success("成功显示点赞点踩状态",commentLike.getStatus());
        }
    }

    /**
     * 删除帖子
     * @param postId 帖子id
     * @return 一个Result结果
     */
    @DeleteMapping("deletePost")
    public Result deletePost(@RequestParam Integer postId){
        log.info("--------------------删除帖子请求--------------------");
        boolean result = postService.removeById(postId);
        if (result){
            return Result.success("删除帖子成功");

        }
        else {
            return Result.error("表中无对应帖子");
        }
    }

    /**
     * 搜索帖子
     * @param page 当前页数
     * @param pageSize 页面大小
     * @param search 搜索内容
     * @param type 搜索类型
     * @return 一个Result结果
     */
    @GetMapping("searchPost")
    public Result searchPost(@RequestParam("page") Integer page,@RequestParam("pageSize") Integer pageSize,@RequestParam("search") String search,@RequestParam("type") String type, @RequestParam("select") String select) {
        log.info("--------------------搜索帖子请求--------------------");
        List<ViewPost> posts;
        if (type.equals("Enrollment")) {
            posts = viewPostService.searchEnrollmentPost(search, page, pageSize, select);
        }
        else {
            posts = viewPostService.searchJobPost(search, page, pageSize, select);
        }
        if (posts == null || posts.isEmpty()) {
            return Result.error("无相关帖子");
        }
        else return Result.success("搜索帖子成功", posts);
    }

    /**
     * 发布帖子（手机端）
     * @param token token令牌
     * @param newPostRequest 发布帖子请求
     * @return 一个result结果
     */
    @PostMapping("newPost")
    public Result newPost(@RequestHeader("token") String token,@RequestBody NewPostRequest newPostRequest){
        log.info("--------------------发布帖子请求--------------------");
        String studentId = Token.inspectOldToken(token);
        if(newPostRequest.getTags().contains(2) && studentService.getById(studentId).getAuthority().equals(0)){
            return Result.error("无发帖权限");
        }
        Post post = new Post();
        post.setStudentId(Integer.valueOf(studentId));
        post.setTitle(newPostRequest.getTitle());
        post.setContent(newPostRequest.getContent());
        post.setStatus(0);
        post.setIsShare(0);
        post.setSharePostId(-1);
        LocalDateTime currentTime = LocalDateTime.now();
        post.setCreatedAt(Timestamp.valueOf(currentTime));
        post.setUpdatedAt(Timestamp.valueOf(currentTime));
        try {
            postService.save(post);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error("数据库错误");
        }
        for (Integer tag: newPostRequest.getTags()){
            PostTag postTag = new PostTag();
            postTag.setTagId(tag);
            postTag.setPostId(post.getPostId());

            try {
                postTagService.save(postTag);
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("数据库错误");
            }
        }
        post.setNickname(studentService.getById(studentId).getNickname());
        return Result.success("成功发布帖子，等待审核中",post);
    }

    /**
     * 发布帖子(PC端)
     * @param token token令牌
     * @param newPostRequest 发布帖子请求
     * @return 一个result结果
     */
    @PostMapping("newPost2")
    public Result newPost2(@RequestHeader("token") String token,@RequestBody NewPostRequest2 newPostRequest){
        log.info("--------------------发布帖子请求--------------------");
        String studentId = Token.inspectOldToken(token);
        if(newPostRequest.getTag().equals(2) && studentService.getById(studentId).getAuthority().equals(0)){
            return Result.error("无发帖权限");
        }
        Post post = new Post();
        post.setStudentId(Integer.valueOf(studentId));
        post.setTitle(newPostRequest.getTitle());
        post.setContent(newPostRequest.getContent());
        post.setStatus(0);
        post.setIsShare(0);
        post.setSharePostId(-1);
        LocalDateTime currentTime = LocalDateTime.now();
        post.setCreatedAt(Timestamp.valueOf(currentTime));
        post.setUpdatedAt(Timestamp.valueOf(currentTime));
        try {
            postService.save(post);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error("数据库错误");
        }
        PostTag postTag1 = new PostTag();
        postTag1.setTagId(newPostRequest.getTag());
        postTag1.setPostId(post.getPostId());

        try {
            postTagService.save(postTag1);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error("数据库错误");
        }
        for (Integer tag: newPostRequest.getTags()){
            PostTag postTag = new PostTag();
            postTag.setTagId(tag);
            postTag.setPostId(post.getPostId());

            try {
                postTagService.save(postTag);
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("数据库错误");
            }
        }
        post.setNickname(studentService.getById(studentId).getNickname());
        return Result.success("成功发布帖子，等待审核中",post);
    }

    /**
     * 根据学生id显示帖子
     * @param studentId 学生id
     * @return 一个Result结果
     */
    @GetMapping("showOtherPosts")
    public Result showOtherPosts(@RequestParam("studentId") String studentId, @RequestParam("page") Integer page1,@RequestParam("pageSize") Integer pageSize){
        log.info("--------------------根据学生id显示帖子请求--------------------");
        QueryWrapper<Post> postQueryWrapper = new QueryWrapper<Post>()
                .eq("student_id",studentId)
                .eq("status",1)
                .orderByDesc("updated_at");
        Page<Post> page = Page.of(page1, pageSize);
        List<Post> posts = postService.list(page,postQueryWrapper);
        if (posts.isEmpty()){
            return Result.error("该用户还未发帖");
        }
        return handlePost(posts,"显示其他用户主页帖子成功");
    }
    /**
     * 根据学生id显示帖子
     * @param token token令牌
     * @return 一个Result结果
     */
    @GetMapping("showSelfPosts")
    public Result showSelfPosts(@RequestHeader("token") String token, @RequestParam("page") Integer page1,@RequestParam("pageSize") Integer pageSize){
        log.info("--------------------根据学生id显示帖子请求--------------------");
        String studentId = Token.inspectOldToken(token);
        QueryWrapper<Post> postQueryWrapper = new QueryWrapper<Post>()
                .eq("student_id",studentId)
                .orderByDesc("updated_at");
        Page<Post> page = Page.of(page1,pageSize);
        List<Post> posts = postService.list(page, postQueryWrapper);
        if (posts.isEmpty()){
            return Result.error("您当前还未发帖");
        }
        return handlePost(posts,"成功获得帖子");
    }

    /**
     * 给帖子列表添加昵称
     * @param posts 帖子列表
     * @param message 成功时显示的信息
     * @return 一个Result结果
     */
    private <T extends PostInterface> Result handlePost(List<T> posts, String message) {
        for (T post: posts){
            Student student;
            try {
                student = studentService.getById(post.getStudentId());
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("数据库错误");
            }
            post.setNickname(student.getNickname());
        }
        return Result.success(message, posts);
    }

    /**
     * 显示待审核帖子
     * @return 一个Result结果
     */
    @GetMapping("showPendingPost")
    public Result showPendingPost(@RequestParam("page") Integer page1,@RequestParam("pageSize") Integer pageSize){
        log.info("--------------------显示待审核帖子请求--------------------");
        QueryWrapper<Post> postQueryWrapper = new QueryWrapper<Post>()
                .eq("status",0)
                .orderByDesc("updated_at");
        Page<Post> page = Page.of(page1, pageSize);
        List<Post> posts = postService.list(page,postQueryWrapper);
        if (posts.isEmpty()){
            return Result.error("无待审核帖子");
        }
        return handlePost(posts,"成功获得待审核帖子");
    }

    /**
     * 审核帖子
     * @param moderatePostRequest 审核帖子的请求类
     * @return 一个Result结果
     */
    @PutMapping("moderatePost")
    public Result moderatePost(@RequestBody ModeratePostRequest moderatePostRequest){
        log.info("--------------------审核帖子请求--------------------");
        Integer postId = moderatePostRequest.getPostId();
        QueryWrapper<Post> postQueryWrapper = new QueryWrapper<Post>()
                .eq("status",0)
                .eq("post_id",postId);
        Post post = postService.getOne(postQueryWrapper);
        if (post == null){
            return Result.error("数据库无对应未审核帖子");
        }
        else if (moderatePostRequest.getType().equals("true")){
            post.setStatus(1);
        }
        else{
            post.setStatus(2);
        }
        postService.updateById(post);
        return Result.success("审核帖子成功");
    }

    /**
     * 根据标签获取帖子
     * @param page 当前页码
     * @param pageSize 页面大小
     * @param tagId 标签id
     * @param type 类型
     * @return 一个result结果
     */
    @GetMapping("getPostsByTag")
    public Result getPostsByTag(@RequestParam("page") Integer page, @RequestParam("pageSize") Integer pageSize,@RequestParam("tagId") Integer tagId,@RequestParam("type") String type){
        log.info("--------------------根据标签获取帖子请求--------------------");
        Integer typeId = type.equals("Enrollment") ? 1:2;
        QueryWrapper<PostTag> postTagQueryWrapper = new QueryWrapper<PostTag>()
                .in("tag_id",tagId,typeId)
                .groupBy("post_id")
                .having("count(post_id) = 2");
        Page<PostTag> page1 = Page.of(page,pageSize);
        List<PostTag> postTags = postTagService.list(page1,postTagQueryWrapper);
        if (postTags.isEmpty()){
            return Result.error("无相应帖子");
        }
        List<Post> posts = new ArrayList<>();
        for (PostTag postTag : postTags){
            Post post = postService.getById(postTag.getPostId());
            posts.add(post);
        }
        return handlePost(posts,"成功获取帖子");
    }
}
